import axios from "axios"
import store from "@/store"
import history from "./history" // 自定义的历史对象信息
import { setToken } from "@/store/actions/user"
import { clearToken } from "./auth"
const instance = axios.create({
  timeout: 5000,
  baseURL: "http://toutiao.itheima.net",
})

instance.interceptors.request.use(
  (config) => {
    // 配置信息 => 注入token
    const {
      user: { token },
    } = store.getState() // 获取整个的redux状态
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

instance.interceptors.response.use(
  (response) => {
    return response ? response.data : response
  },
  (error) => {
    // token失效 => status 401
    if (error.response?.status === 401) {
      // 清空本地缓存  清空redux
      clearToken() // 清空本地缓存
      // 跳到登录页
      store.dispatch(setToken("")) // 将redux的token设置为 ""
      history.push({
        pathname: "/login",
        state: {
          from: history.location.pathname, // 传递当前页面的路径
        },
      })
    }
    return Promise.reject(error)
  }
)

export default instance
